package gateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
import com.easy.common.service.ITokenService;
import com.easy.common.util.Result;
import com.easy.common.util.SYS;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
@Component
public class GatewayGlobalFilter implements GlobalFilter, Ordered {
    @DubboReference
    ITokenService tokenService;
    @Override
    public int getOrder() {
        return 0;
    }

    //放行的地址(白名单)
    private static final List<String> ALLOWED_PATHS =
            Arrays.asList("/login/admin/dologin","/login/user/dologin", "/login/captcha");
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("GatewayGlobalFilter");
        ServerHttpRequest request = exchange.getRequest();
         URI uri =request.getURI();
         String path =uri.getPath();//访问路径
        System.out.println("path:"+path);
        if(ALLOWED_PATHS.contains(path)){
            //如果访问路径是白名单中的路径，则直接放行
            return chain.filter(exchange);
        }
        //验证有没有登录
        //获取token
        String token = request.getHeaders().getFirst(SYS.AUTHORIZATION_HEADER);
        //判断token是否为空,还要判断Token是否有效,如果认证模块,在此通过Dubbo服务获取token是否有效
        if(token==null||!tokenService.checkToken(token)){
            return unauthorizedResponse(exchange,Result.fail(401,"未认证"));
        }
        //验证token通过,直接放行
        return chain.filter(exchange);
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, Result result) {
        String json = JSON.toJSONString(result);
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json");
        return response.writeWith(Mono.just(response.bufferFactory()
                .wrap(json.getBytes())));
    }
}
